package alijk.dataView.services;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleTrigger;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.triggers.SimpleTriggerImpl;
/**
 * 异步任务调度
 * @time 2014年12月10日 下午4:39:22
 * @author CheWenliang
 */
public class QuartzTaskUtil {
	private static Scheduler scheduler = null;
	
	public static Map<String, String> taskMap = new HashMap<String, String>();
	
	private QuartzTaskUtil(){}
	
	/**
	 * 执行任务
	 * @param taskName
	 * @param triggerName
	 * @throws SchedulerException
	 * @throws ParseException
	 */
	public static  void startJob(String taskName,String triggerName,Map<String, String> params) throws SchedulerException, ParseException {
		Scheduler sched = getScheduler();
		JobKey jobKey = new JobKey(triggerName, taskName);
		
		//设置参数
		sched.getContext().put("params", params);
		
		JobDetail jobDetail = JobBuilder.newJob(QuartzJobOut.class)
				.withIdentity(jobKey).build();
		SimpleTrigger simpleTrigger = new SimpleTriggerImpl(taskName,  new Date(new Date().getTime() + 1000L)); 
		sched.scheduleJob(jobDetail, simpleTrigger);

		if (!sched.isStarted()) {
			sched.start();
		}
	}
	
	private  static synchronized Scheduler getScheduler()
			throws SchedulerException {
		if (scheduler == null) {
			scheduler = new StdSchedulerFactory().getScheduler();
		}
		return scheduler;
	}
	/**
	 * 清除昨天的任务名
	 */
	public static void  clearTaskMap(){
		Calendar cal = Calendar.getInstance();
		int today = cal.get(Calendar.DAY_OF_MONTH);
		Calendar cal_t = Calendar.getInstance();
		Iterator<String> iter = QuartzTaskUtil.taskMap.keySet().iterator();
		while(iter.hasNext()){
			String key = iter.next();
			Long time = Long.valueOf(QuartzTaskUtil.taskMap.get(key));
			Date date = new Date(time);
			cal_t.setTime(date);
			int b_day = cal_t.get(Calendar.DAY_OF_MONTH);
			if(b_day < today){
				QuartzTaskUtil.taskMap.remove(key);
			}
		}
	}
}
